<template>
  <view>
    <navbar/>
    <u--form ref="form" :model="temp" label-position="top">
      <u-form-item label="标题:" prop="title" required>
        <u--input v-model="temp.title" placeholder="请输入标题"/>
      </u-form-item>
      <u-form-item label="用户:" prop="userId" required>
        <system-user v-model="temp.userId" placeholder="请选择用户"/>
      </u-form-item>
      <u-form-item label="部门:" prop="organizationId">
        <system-organization v-model="temp.organizationId"/>
      </u-form-item>
      <u-form-item label="时间:" prop="date">
        <date-picker v-model="temp.date" placeholder="请选择发生时间" type="date" pattern="{y}-{m}-{d}"/>
      </u-form-item>
      <u-form-item label="内容:" prop="content">
        <u--textarea v-model="temp.content" maxlength="-1" height="80px" placeholder="请输入内容"/>
      </u-form-item>
      <u-form-item label="图片:" prop="image">
        <upload-image v-model="temp.image" dir="event"/>
      </u-form-item>
      <u-button :loading="loading" class="submit-button" type="primary" shape="circle" @click="submit">提交</u-button>
    </u--form>
  </view>
</template>
<script>
import SystemUser from '@/components/System/systemUser'
import DatePicker from '@/components/Picker/datePicker.vue'
import UploadImage from '@/components/Upload/uploadImage'
import SystemOrganization from '@/components/System/systemOrganization.vue'
import { addEvent, getEventDetail, updateEvent } from '@/api/event/event'

export default {
  name: 'EventForm',
  components: {
    SystemOrganization,
    SystemUser,
    DatePicker,
    UploadImage
  },
  data() {
    return {
      loading: false,
      temp: {},
      rules: {
        title: [{ required: true, message: '标题为必填项' }],
        userId: [{ required: true, message: '用户为题为必填项' }]
      }
    }
  },
  onLoad(query) {
    this.temp.id = query.id
    if (this.temp.id) {
      this.getDetails(query.id)
    }
  },
  onReady() {
    this.$refs.form.setRules(this.rules)
  },
  methods: {
    // 获取详情
    getDetails(id) {
      getEventDetail(id).then(response => {
        this.temp = response.data.data
      })
    },
    // 提交表单
    submit() {
      if (this.isNull(this.rules)) {
        !this.temp.id ? this.create() : this.update()
        return
      }
      this.$refs.form.validate().then(() => {
        !this.temp.id ? this.create() : this.update()
      })
    },
    // 新建
    create() {
      this.loading = true
      addEvent(this.temp).then(response => {
        this.loading = false
        if (response.data.success) {
          this.$uni.showToast(response.data.msg)
          this.$uni.goBack()
        }
      })
    },
    // 更新
    update() {
      this.loading = true
      updateEvent(this.temp).then(response => {
        this.loading = false
        if (response.data.success) {
          this.$uni.showToast(response.data.msg)
          this.$uni.goBack()
        }
      })
    }
  }
}
</script>

